package cn.antblog.base.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

/**
 * @author yangjy
 * @version 1.0
 * @description: CGlib创建动态代理的原理：⽗⼦继承关系创建代理对象，原始类作为⽗类，代理类作为⼦类，
 * 这样既可以保证2者⽅法⼀致，同时在代理类中提供新的实现(额外功能+原始⽅法)
 * @date 2022/4/21 15:20
 */
public class TestCglib {
    public static void main(String[] args) {
        // 1. 创建原始对象
        TestService testService = new TestService();
        //2 .通过cglib创建动态代理对象
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(testService.getClass().getClassLoader());
        enhancer.setSuperclass(testService.getClass());
        MethodInterceptor methodInterceptor = (o, method, args1, methodProxy) -> {
            //等同于 InvocationHandler ---invoke
            System.out.println(" log= ");
            Object invoke = method.invoke(testService, args1);
            return invoke;
        };

        enhancer.setCallback(methodInterceptor);

        TestService o = (TestService) enhancer.create();
        o.login("yjy", "123");

    }

}
